import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:happy_around_us/RongCloud/RCConfig.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:rongcloud_call_wrapper_plugin/rongcloud_call_wrapper_plugin.dart';
import 'package:rongcloud_im_wrapper_plugin/rongcloud_im_wrapper_plugin.dart';

final TAG = '日志  ';

class RCIMPage extends StatefulWidget {
  RCIMPage(this.isCall);

  bool isCall;

  @override
  State<RCIMPage> createState() => _RCIMPageState();
}

class _RCIMPageState extends State<RCIMPage> {
  RCIMIWEngine? _engine;
  RCCallEngine? _callEngine;
  RCIMIWConnectionStatus _status = RCIMIWConnectionStatus.signOut;
  int loginIndex = 0;
  var loginInfo = '';

  late RCIMIWConnectCallback _connectCallback;
  late RCIMIWSendMessageCallback _sendMessageCallback;

  final _anotherController = TextEditingController();
  final _msgController = TextEditingController();

  //  展示的信息
  final _showController = TextEditingController();
  var _showMessages = '';

  addShowMsg(String msg) {
    _showMessages += '\n' + TAG + msg;
    // setState(() => _showMessages += '\n' + msg);
    setState(() {
      _showController.text = _showMessages;
      print('_showController.text  = ' + _showController.text);
    });
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Divider(height: 50),
        Text('IM引擎状态：' + (_engine != null ? '已初始化' : '未初始化')),
        Text('Call引擎状态：' + (_callEngine != null ? '已初始化' : '未初始化')),
        OutlinedButton(
          child: Text('去初始化引擎'),
          onPressed: () {
            initRongCloud();
          },
        ),
        Divider(height: 30),
        OutlinedButton(
          child: Text(
            '登录者点击切换：【${loginIndex}】\n\ns${RCConfig.LoginTokens[loginIndex]}',
            textAlign: TextAlign.center,
          ),
          onPressed: () {
            setState(() => loginIndex = (loginIndex + 1) % 3);
          },
        ),
        OutlinedButton(
          child: Text('去登录'),
          onPressed: () {
            login();
          },
        ),
        Text('当前连接状态：${_status.toString()}'),
        Text('已登录者信息：${loginInfo}'),
        Divider(height: 30),
        TextField(
          controller: _anotherController,
          autofocus: true,
          decoration: InputDecoration(
            labelText: "请输入对方id",
            hintText: "请输入对方id",
          ),
        ),
        //  IM消息
        if (!widget.isCall)
          TextField(
            controller: _msgController,
            autofocus: true,
            decoration: InputDecoration(
              labelText: "请输入要发送的信息",
              hintText: "请输入要发送的信息",
              prefixIcon: Icon(Icons.person),
            ),
          ),
        if (!widget.isCall)
          OutlinedButton(
            child: Text('点击发送'),
            onPressed: () {
              sendMessage();
            },
          ),
        if (!widget.isCall)
          OutlinedButton(
            child: Text('getConversations'),
            onPressed: () {
              getConversations();
            },
          ),

        if (widget.isCall)
          OutlinedButton(
            child: Text('startCall'),
            onPressed: () {
              startCall();
            },
          ),
        if (widget.isCall)
          OutlinedButton(
            child: Text('accept'),
            onPressed: () {
              accept();
            },
          ),
        Expanded(
          child: SingleChildScrollView(
            child: Text(_showMessages),
          ),
        ),
      ],
    );
  }

  initRongCloud() async {
    final isGranted = await Permission.camera.request().isGranted;
    addShowMsg('Permission.camera: ${isGranted}');

    print('initRongCloud: start');
    //  融云初始化
    RCIMIWEngineOptions options = RCIMIWEngineOptions.create();
    final engine = await RCIMIWEngine.create(RCConfig.appKey, options);
    setState(() => _engine = engine);
    addShowMsg('initRongCloud: _engine');

    //  连接状态
    _engine?.onConnectionStatusChanged = (RCIMIWConnectionStatus? status) {
      addShowMsg('onConnectionStatusChanged = ${status.toString()}');
      if (status != null) {
        setState(() => _status = status!);
      }
    };

    //  登录回调
    _connectCallback = RCIMIWConnectCallback(
      onDatabaseOpened: (int? code) {
        addShowMsg('onDatabaseOpened code = ${code}');
      },
      onConnected: (int? code, String? userId) {
        addShowMsg('onConnected code = ${code}   userId = ${userId}');
        setState(() => loginInfo = 'code = ${code}   userId = ${userId}');
      },
    );

    //  消息回调
    _engine?.onMessageReceived = (
      RCIMIWMessage? message,
      int? left,
      bool? offline,
      bool? hasPackage,
    ) {
      if (message != null) {
        final msg = message as RCIMIWTextMessage;

        addShowMsg(
            'onMessageReceived left(${left})  offline(${offline})  hasPackage${hasPackage}  ${msg.text}');
      }
    };

    //  发送消息回调
    _sendMessageCallback = RCIMIWSendMessageCallback(
      onMessageSaved: (RCIMIWMessage? message) {
        if (message != null) {
          final msg = message as RCIMIWTextMessage;
          addShowMsg('onMessageSaved message = ${msg.text ?? ''}');
        }
      },
      onMessageSent: (int? code, RCIMIWMessage? message) {
        if (message != null) {
          final msg = message as RCIMIWTextMessage;
          addShowMsg(
              'onMessageSent code = ${code}, message = ${msg.text ?? ''}');
        }
      },
    );

    //  Call初始化
    final callEngine = await RCCallEngine.create();
    setState(() => _callEngine = callEngine);
    addShowMsg('initRongCloud-Call: _callEngine');

    /// 监听通话呼入
    _callEngine?.onReceiveCall = (RCCallSession session) {
      /// session 通话实体
      addShowMsg('onReceiveCall ${session.targetId}');
    };

    /// 通话拨出监听
    _callEngine?.onCallDidMake = () {
      addShowMsg('onCallDidMake');
    };

    /// 通话建立监听
    _callEngine?.onConnect = () {
      addShowMsg('onConnect');
    };

    /// 通话断开监听
    _callEngine?.onDisconnect = (RCCallDisconnectReason reason) {
      /// reason 断开原因
      addShowMsg('onDisconnect: ${reason.name}');
    };

    /// 设置通话异常监听
    _callEngine?.onCallError = (int errorCode) {
      /// errorCode 异常错误码
      addShowMsg('onCallError: ${errorCode}');
    };

    /// 设置摄像头操作监听
    _callEngine?.onEnableCamera = (RCCallCamera camera, bool enable) {
      /// camera 当前摄像头
      /// enable 开启状态
      addShowMsg('onEnableCamera: ${camera.name}   ${enable}');
    };

    /// 设置切换摄像头监听
    _callEngine?.onSwitchCamera = (RCCallCamera camera) {
      /// camera 当前摄像头
      addShowMsg('onSwitchCamera: ${camera.name}');
    };

    /// 设置被叫端正在振铃监听
    _callEngine?.onRemoteUserDidRing = (String userId) {
      /// userId 正在振铃的用户 ID
      addShowMsg('onRemoteUserDidRing: ${userId}');
    };

    /// 设置用户操作麦克风监听
    _callEngine?.onRemoteUserDidChangeMicrophoneState = (RCCallUserProfile user, bool enable) {
      /// user 操作麦克风的用户
      /// enable 麦克风开启状态
      addShowMsg('onRemoteUserDidChangeMicrophoneState: ${user.toString()}   ${engine}');
    };

    /// 设置用户操作摄像头监听
    _callEngine?.onRemoteUserDidChangeCameraState = (RCCallUserProfile user, bool enable) {
      /// user 操作摄像头的用户
      /// enable 摄像头开启状态
      addShowMsg('onRemoteUserDidChangeCameraState: ${user.toString()}   ${engine}');
    };

    /// 设置视频转音频监听
    _callEngine?.onRemoteUserDidChangeMediaType = (RCCallUserProfile user, RCCallMediaType mediaType) {
      /// user 触发媒体类型转换的用户
      /// mediaType 转换后的媒体类型
      addShowMsg('onRemoteUserDidChangeMediaType: ${user.toString()}   ${mediaType.name}');
    };

    /// 设置通话网络质量监听
    _callEngine?.onNetworkQuality = (RCCallUserProfile user, RCCallNetworkQuality quality) {
      /// user 用户信息
      /// quality 网络质量
      addShowMsg('onNetworkQuality: ${user.toString()}   ${quality.name}');
    };

    /// 设置通话音量监听
    _callEngine?.onAudioVolume = (RCCallUserProfile user, int volume) {
      /// user 用户信息
      /// volume 当前音量
      addShowMsg('onAudioVolume: ${user.toString()}   ${volume}');
    };
  }

  login() async {
    //  登录(iOS使用用户1，Android使用用户2)
    int? ret = await _engine?.connect(
      RCConfig.LoginTokens[loginIndex],
      RCConfig.timeout,
      callback: _connectCallback,
    );
    addShowMsg('login ret = ${ret}');
  }

  sendMessage() async {
    RCIMIWTextMessage? textMessage = await _engine?.createTextMessage(
      RCIMIWConversationType.private,
      _anotherController.text,
      null,
      _msgController.text,
    );

    _engine?.sendMessage(textMessage!, callback: _sendMessageCallback);
  }

  getConversations() async {
    var callback = IRCIMIWGetConversationsCallback(
      onSuccess: (List<RCIMIWConversation>? t) {
        addShowMsg('查询消息列表： ${t == null}   ${t?.length}');
        if (t != null) {
          t.forEach((conversation) {
            var str = conversation.targetId ?? '';
            if (conversation.lastMessage != null) {
              str += '  ';
              str += (conversation.lastMessage as RCIMIWTextMessage).text ?? '';
            }
            addShowMsg(str);
          });
        }
      },
      onError: (int? code) {},
    );

    List<RCIMIWConversationType> conversationTypes = [];
    conversationTypes.add(RCIMIWConversationType.private);
    // conversationTypes.add(RCIMIWConversationType.private);
    int? ret = await _engine?.getConversations(
      conversationTypes,
      null,
      0,
      10,
      callback: callback,
    );

    addShowMsg('getConversations： ret = ${ret}');
  }

  getConversation() async {
    var callback = IRCIMIWGetConversationCallback(
      onSuccess: (RCIMIWConversation? conversation) {
        addShowMsg('查询消息列表： ${conversation == null}');
        if (conversation != null) {
          var str = conversation.targetId ?? '';
          if (conversation.lastMessage != null) {
            str += '  ';
            str += (conversation.lastMessage as RCIMIWTextMessage).text ?? '';
          }
          addShowMsg(str);
        }
      },
      onError: (int? code) {},
    );

    List<RCIMIWConversationType> conversationTypes = [];
    conversationTypes.add(RCIMIWConversationType.private);
    int? ret = await _engine?.getConversation(
      RCIMIWConversationType.private,
      '2',
      null,
      callback: callback,
    );

    addShowMsg('getConversation： ret = ${ret}');
  }

  startCall() async {
    RCCallVideoConfig videoConfig = RCCallVideoConfig.create(
      /// 指定开启后置摄像头
      defaultCamera: RCCallCamera.front,
    );
    /// 配置视频参数
    _callEngine?.setVideoConfig(videoConfig);

    /// 通话媒体类型
    RCCallMediaType mediaType = RCCallMediaType.audio_video;
    _callEngine?.startCall(_anotherController.text, mediaType);
  }

  accept() async {
    /// 通话媒体类型
    _callEngine?.accept();
  }

  void _toCallingPage(BuildContext context) {
    FocusScope.of(context).requestFocus(new FocusNode());
    Navigator.pushNamed(context, '');
  }

  // Widget rcCallView() {
  //   return RCCallView();
  // }
}
